<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command;

use app\enum\CommonEnum;
use app\enum\QqEnum;
use app\enum\TokenEnum;
use app\model\CrontabTaskModel;
use app\model\QqAdvertiserDailyStatHistoryModel;
use app\model\QqAdvertiserDailyStatModel;
use app\service\BaseService;
use app\service\client\AccountService;
use app\service\CrontabTaskService;
use app\service\qq\FinanceService;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cache;

class QqAdvertiserDailyStatRecallWork extends BaseWork implements DailyStatWork
{
    public string $tag;

    public array $clientAccountInfo = [];

    /**
     * 设置任务标识.
     * @param mixed $tag
     */
    public function setTag($tag = ''): bool
    {
        if (! is_null($tag)) {
            $this->tag = strval($tag);
        }
        return true;
    }

    /**
     * 获取任务标识.
     */
    public function getTag(): string
    {
        return $this->tag;
    }

    /**
     * 获取脚本名.
     */
    public function getCommandName(): string
    {
        return $this->getName();
    }

    /**
     * 获取定时任务.
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getCrontabTaskInfo(): CrontabTaskModel
    {
        $where = [
            ['task_name', '=', $this->getName()],
            //            ['tag', '=', $this->getTag()],
        ];

        $obj = new CrontabTaskModel();
        $model = $obj->where($where)->field(true)->find();
        return $model instanceof CrontabTaskModel ? $model : $obj;
    }

    protected function configure()
    {
        // 指令配置
        $this->setName('qq_advertiser_daily_stat_recall_work');
        $this->setDescription('广点通-账户日流水拉取回溯');
        $this->addArgument('type', Argument::REQUIRED, '类型  1：主表 2：历史数据表');
        $this->addArgument('start_date', Argument::OPTIONAL, '开始日期');
        $this->addArgument('end_date', Argument::OPTIONAL, '结束日期');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        ini_set('memory_limit', '-1');

        $output->writeln('=======广点通-账户日流水拉取开始' . date('Y-m-d H:i:s', time()) . '=======');
        $type = intval($input->getArgument('type'));
        $startDates = $input->getArgument('start_date');
        $endDates = $input->getArgument('end_date');

        if (! $startDates || ! $endDates) {
            $output->writeln('===========开始时间，结束时间都必须存在！===========');
            return;
        }

        if ($startDates > $endDates) {
            $output->writeln('===========开始时间必须小于结束时间！===========');
            return;
        }
        $redis = Cache::store('redis')->handler();
        $redisKey = 'task:qq_fund_recall';
        $date = createDateRange($startDates, $endDates);
        $dateR = array_chunk($date, 10);
        for ($i = 0; $i < 30; ++$i) {
            $account = $redis->lPop($redisKey);
            if ($account) {
                $account = explode('_', $account);
                $advertiserId = $account[0];
                $execNum = intval($account[1]);
                //  获取账户信息
                $this->clientAccountInfo = BaseService::getClientAccountInfo($advertiserId);
                foreach ($dateR as $da) {
                    $tmp = true;
                    $startDate = $da[0];
                    $endDate = $da[count($da) - 1];
                    $page = 0;
                    while (true) {
                        $token = AccountService::getToken(CommonEnum::QQ_MEDIA, $advertiserId, TokenEnum::QQ_API_TOKEN_FUND_COST);
                        if (! $token) {
                            CrontabTaskService::fallPushList($redis, $redisKey, $advertiserId, $execNum, 'token获取失败');
                            $tmp = false;
                            break;
                        }
                        ++$page;
                        $result = $this->_getServiceAdvertiserDailyFlow($token, $advertiserId, $startDate, $endDate, $page);

                        if (! $result) {
                            $err = ['params' => ['token' => $token, 'advertiserId' => $advertiserId, 'startDate' => $startDate, 'endDate' => $endDate, 'page' => $page], 'response' => FinanceService::getError(0)];
                            $output->writeln('=======error:' . json_encode($err, JSON_UNESCAPED_UNICODE) . '=======');
                            CrontabTaskService::fallPushList($redis, $redisKey, $advertiserId, $execNum, json_encode($err, JSON_UNESCAPED_UNICODE));
                            $tmp = false;
                            usleep(rand(800000, 1500000));
                            break;
                        }
                        if ($result['code'] != 0) {
                            $err = ['params' => ['token' => $token, 'advertiserId' => $advertiserId, 'startDate' => $startDate, 'endDate' => $endDate, 'page' => $page], 'response' => ''];
                            $output->writeln('=======error:' . json_encode($err, JSON_UNESCAPED_UNICODE) . '=======');
                            CrontabTaskService::fallPushList($redis, $redisKey, $advertiserId, $execNum, json_encode($err, JSON_UNESCAPED_UNICODE));
                            $tmp = false;
                            usleep(rand(800000, 1500000));
                            break;
                        }

                        $list = $result['data']['list'];
                        if (count($list) == 0) {
                            break;
                        }

                        foreach ($list as $v) {
                            $statDate = intval(date('Ymd', $v['time']));
                            $statInfo = $this->_getStatInfo($advertiserId, $statDate, $v['fund_type'], $type);
                            if (! empty($statInfo)) {
                                if (! $this->_isStatDataUpdate($statInfo, $v)) {
                                    $result = $this->_updateStatData($statInfo['id'], $v, $type);
                                }
                            } else {
                                $result = $this->_insertStatData($advertiserId, $v, $type);
                            }

                            /*if (! $result) {
                                return self::getError(0);
                            }*/
                        }
                    }
                    if (! $tmp) {
                        break;
                    }
                }

            }
        }

        $output->writeln('=======广点通-账户日流水拉取结束' . date('Y-m-d H:i:s', time()) . '=======');
        $output->writeln('success');
    }

    private function _getField(): array
    {
        return ['account_id', 'time', 'deposit', 'paid', 'trans_in', 'trans_out', 'credit_modify', 'balance', 'preauth_balance'];
    }

    /**
     * 获取获取广告账户流水信息.
     * @param string $token token
     * @param string $advertiserId 账户ID
     * @param string $startDate 开始时间
     * @param string $endDate 结束 时间
     * @return bool|mixed|string
     */
    private function _getServiceAdvertiserDailyFlow(string $token = '', string $advertiserId = '', string $startDate = '', string $endDate = '', int $page = 1)
    {
        $params = [
            'access_token' => $token,
            'account_id' => $advertiserId,
            'date_range' => ['start_date' => $startDate, 'end_date' => $endDate],
            'fields' => $this->_getField(),
            'page' => $page,
            'page_size' => QqEnum::MAX_PAGE_SIZE,
        ];

        return FinanceService::getAdvertiserDailyFlow($params);
    }

    /**
     * 判断是否需要更新.
     * @param array $oldData 旧数据
     * @param array $newData 新数据
     */
    private function _isStatDataUpdate(array $oldData = [], array $newData = []): bool
    {
        $one = $oldData['balance'] == $newData['balance'];
        $two = $oldData['paid'] == $newData['paid'];
        $three = $oldData['trans_in'] == $newData['trans_in'];
        $four = $oldData['deposit'] == $newData['deposit'];

        if ($one && $two && $three && $four) {
            return true;
        }

        return false;
    }

    /**
     * 获取广告账户流水信息.
     * @param string $advertiserId 账户ID
     * @param int $statDate 日期
     * @throws
     */
    private function _getStatInfo(string $advertiserId = '', int $statDate = 0, string $fundType = '', int $type = 1): array
    {
        $where = [
            ['advertiser_id', '=', $advertiserId],
            ['stat_date', '=', $statDate],
            ['fund_type', '=', $fundType],
        ];
        if ($type == 1) {
            $info = (new QqAdvertiserDailyStatModel())->where($where)->field(true)->find();
        } elseif ($type == 2) {
            $info = (new QqAdvertiserDailyStatHistoryModel())->where($where)->field(true)->find();
        }
        if (! $info) {
            return [];
        }

        return $info->toArray();
    }

    /**
     * 修改广告账户流水信息.
     * @param int $id 主键ID
     * @param array $params 参数
     */
    private function _updateStatData(int $id, array $params = [], int $type = 1)
    {
        try {
            $data = [
                'fund_type' => $params['fund_type'], // 资金账户类型
                'time' => $params['time'], // 记录对应的时间（时间戳）
                'deposit' => $params['deposit'], // 总存入，单位为分
                'paid' => $params['paid'], // 总支出，单位为分
                'trans_in' => $params['trans_in'], // 总转入，单位为分
                'trans_out' => $params['trans_out'], // 总转出，单位为分
                'credit_modify' => $params['credit_modify'], //	授信调整，单位为分
                'balance' => $params['balance'], // 日终结余，单位为分。如果无法获取余额则不返回本字段。
                'preauth_balance' => $params['preauth_balance'], // 预授权额度，单位为分。
                'cost' => 0,
                'cash_cost' => 0,
                'update_time' => time(),
            ];
            $paid = $params['paid'] / 100;
            if ($params['fund_type'] == QqEnum::FUND_TYPE_CASH) {// 现金消耗
                $data['cost'] += $paid;
                $data['cash_cost'] += $paid;
            } elseif ($params['fund_type'] == QqEnum::FUND_TYPE_VIRTUAL) {// 补偿虚拟金消耗
                $data['cost'] += $paid;
            } elseif ($params['fund_type'] == QqEnum::FUND_TYPE_ROLL) {// 固定信用金消耗
                $data['cost'] += $paid;
                $data['cash_cost'] += $paid;
            }
            if ($type == 1) {
                return (new QqAdvertiserDailyStatModel())->where('id', $id)->update($data);
            }
            if ($type == 2) {
                return (new QqAdvertiserDailyStatHistoryModel())->where('id', $id)->update($data);
            }


        } catch (\Exception $e) {
            return self::setError($e->getMessage());
        }
    }

    /**
     * 插入广告账户流水信息.
     * @param string $advertiserId 账户ID
     * @param array $params 参数
     */
    private function _insertStatData(string $advertiserId = '', array $params = [], int $type = 1)
    {
        try {
            $data = [
                'advertiser_id' => $advertiserId, // 账户ID
                'stat_date' => date('Ymd', $params['time']), // 时间
                'fund_type' => $params['fund_type'], // 资金账户类型
                'time' => $params['time'], // 记录对应的时间（时间戳）
                'deposit' => $params['deposit'], // 总存入，单位为分
                'paid' => $params['paid'], // 总支出，单位为分
                'trans_in' => $params['trans_in'], // 总转入，单位为分
                'trans_out' => $params['trans_out'], // 总转出，单位为分
                'credit_modify' => $params['credit_modify'], //	授信调整，单位为分
                'balance' => $params['balance'], // 日终结余，单位为分。如果无法获取余额则不返回本字段。
                'preauth_balance' => $params['preauth_balance'], // 预授权额度，单位为分。
                'cost' => 0,
                'cash_cost' => 0,
                'create_time' => time(),
                'project_id' => $this->clientAccountInfo['project_id'],
                'staff_id' => $this->clientAccountInfo['staff_id'],
            ];
            $paid = $params['paid'] / 100;
            if ($params['fund_type'] == QqEnum::FUND_TYPE_CASH) {// 现金消耗
                $data['cost'] += $paid;
                $data['cash_cost'] += $paid;
            } elseif ($params['fund_type'] == QqEnum::FUND_TYPE_VIRTUAL) {// 补偿虚拟金消耗
                $data['cost'] += $paid;
            } elseif ($params['fund_type'] == QqEnum::FUND_TYPE_ROLL) {// 固定信用金消耗
                $data['cost'] += $paid;
                $data['cash_cost'] += $paid;
            }
            if ($type == 1) {
                return (new QqAdvertiserDailyStatModel())->insert($data);
            }
            if ($type == 2) {
                return (new QqAdvertiserDailyStatHistoryModel())->insert($data);
            }

        } catch (\Exception $e) {
            dump($e);
            return self::setError($e->getMessage());
        }
    }

    /**
     * 参数初始化.
     */
    private function _initParam(array $params = []): array
    {
        $now = time();
        $params['timestamp'] = $now;
        $params['nonce'] = uniqid(strval($now));

        return $params;
    }
}
